package com.sso.controller;

import com.sso.pojo.User;
import com.sso.utils.LoginCacheUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;

/**
 * @author xiaoer
 * @date 2020/11/18 14:01
 */
@Controller
@RequestMapping("/login")
public class LoginController {

    private static Set<User> users = new HashSet<>();
    static {
        users.add(new User(1,"aa","aa"));
        users.add(new User(2,"bb","bb"));
        users.add(new User(3,"cc","cc"));
    }

    @PostMapping()
    public String login(User user, HttpSession session, HttpServletResponse response){
        String target = (String) session.getAttribute("target");
        Optional<User> loginUser =  users.stream().filter(users -> users.getUsername().equals(user.getUsername()) &&
                users.getPassword().equals(user.getPassword())).findFirst();
        if(loginUser.isPresent()){
            //登录成功,保存登录信息
            String token = UUID.randomUUID().toString();
            Cookie cookie = new Cookie("TOKEN", token);
            //所有子系统的 顶级域名 共享session
            cookie.setDomain("localhost");
            response.addCookie(cookie);
            LoginCacheUtil.loginUser.put(token,loginUser.get());
        }else{
            //登录失败
            session.setAttribute("msg","账号或密码错误");
            return "login";
        }
        return "redirect:"+target;
    }

    /**
     * 子系统访问这个接口获取登录用户
     * @param token
     * @return
     */
    @GetMapping("/info")
    @ResponseBody
    public ResponseEntity<User> getUserInfo(String token){
        if(!StringUtils.isEmpty(token)){
            User user = LoginCacheUtil.loginUser.get(token);
            return ResponseEntity.ok(user);
        }
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }
}
